package spring.boot.adminx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import spring.boot.adminx.model.WxMiniAppConfig;
import spring.boot.adminx.service.WxMiniAppConfigService;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/wx/admin/config")
public class WxMiniAppConfigController {

    @Autowired
    private WxMiniAppConfigService wxMiniAppConfigService;

    @GetMapping("list/{wxMiniAppId}/{type}")
    public String list(@PathVariable Long wxMiniAppId, @PathVariable String type, Model model){
        QueryWrapper<WxMiniAppConfig> wrapper = new QueryWrapper<>();
        wrapper.eq("wx_mini_app_id",wxMiniAppId);
        wrapper.eq("type",type);
        List<WxMiniAppConfig> list = wxMiniAppConfigService.list(wrapper);
        model.addAttribute("list", list);
        model.addAttribute("wxMiniAppId", wxMiniAppId);
        model.addAttribute("type", type);
        return "config/list";
    }

    @PostMapping("enable/{id}/{enable}")
    @ResponseBody
    public boolean enable(@PathVariable Long id, @PathVariable Integer enable){
        WxMiniAppConfig wxMiniAppConfig = new WxMiniAppConfig();
        wxMiniAppConfig.setId(id);
        wxMiniAppConfig.setEnable(enable);
        return wxMiniAppConfigService.updateById(wxMiniAppConfig);
    }

    @PostMapping("insert")
    public String insert(WxMiniAppConfig wxMiniAppConfig){
        wxMiniAppConfig.setId(IdWorker.getId());
        wxMiniAppConfig.setEnable(1);
        wxMiniAppConfig.setCreateTime(new Date());
        if ("FIRST_PAGE_URL".equals(wxMiniAppConfig.getType())){
            wxMiniAppConfig.setTypeRemark("首页链接配置");
        }else if ("WORDS_CONFIG".equals(wxMiniAppConfig.getType())){
            wxMiniAppConfig.setTypeRemark("文案配置");
        }
        wxMiniAppConfigService.save(wxMiniAppConfig);
        return "redirect:/wx/admin/config/list/"+wxMiniAppConfig.getWxMiniAppId()+"/"+wxMiniAppConfig.getType();
    }


    @PostMapping("delete/{id}")
    @ResponseBody
    public boolean delete(@PathVariable Long id){
        return wxMiniAppConfigService.removeById(id);
    }

}
